package com.asktgapp.hxsg;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.model.UserInfoVO;
import com.asktgapp.modulebase.common.util.LogUtil;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.ChatActivity;
import com.asktgapp.user.activity.MainActivity;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.model.EaseNotifier;
import com.hyphenate.easeui.utils.EaseCommonUtils;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class BiuEaseHelper {
    /**
     * data sync listener
     */
    public interface DataSyncListener {
        /**
         * sync complete
         *
         * @param success true：data sync successful，false: failed to sync data
         */
        void onSyncComplete(boolean success);
    }

    protected static final String TAG = "DemoHelper";

    private EaseUI easeUI;

    /**
     * EMEventListener
     */
    protected EMMessageListener messageListener = null;

    private Map<String, EaseUser> contactList = new HashMap<>();

    private static BiuEaseHelper instance = null;

    private String username;

    private Context appContext;

    private BiuEaseHelper() {
    }

    public synchronized static BiuEaseHelper getInstance() {
        if (instance == null) {
            instance = new BiuEaseHelper();
        }
        return instance;
    }

    /**
     * init helper
     *
     * @param context application context
     */
    public void init(Context context) {
        EMOptions options = initChatOptions();
        //use default options if options is null
        if (EaseUI.getInstance().init(context, options)) {
            appContext = context;

            //debug mode, you'd better set it to false, if you want release your App officially.
            EMClient.getInstance().setDebugMode(com.asktgapp.BuildConfig.DEBUG);
            //get easeui instance
            easeUI = EaseUI.getInstance();
            //to set user's profile and avatar
            setEaseUIProviders();

        }
        registerMessageListener();
        if (easeUI != null)
            easeUI.getNotifier().setNotificationInfoProvider(new EaseNotifier.EaseNotificationInfoProvider() {

                @Override
                public String getTitle(EMMessage message) {
                    //修改标题,这里使用默认
                    return "剪工";
                }

                @Override
                public int getSmallIcon(EMMessage message) {
                    //设置小图标，这里为默认
                    return R.mipmap.logo;
                }

                @Override
                public String getDisplayedText(EMMessage message) {
                    // 设置状态栏的消息提示，可以根据message的类型做相应提示
                    String ticker = EaseCommonUtils.getMessageDigest(message, appContext);
                    if (message.getType() == EMMessage.Type.TXT) {
                        ticker = ticker.replaceAll("\\[.{2,3}\\]", "[表情]");
                    }
                    EaseUser user = getUserInfo(message.getFrom());
                    if (user != null) {
                        return getUserInfo(message.getFrom()).getNickname() + ": " + ticker;
                    } else {
                        return message.getFrom() + ": " + ticker;
                    }
                }

                @Override
                public String getLatestText(EMMessage message, int fromUsersNum, int messageNum) {
                    // return fromUsersNum + "个基友，发来了" + messageNum + "条消息";
                    if (message.getType() == EMMessage.Type.TXT) {
                        String s = message.getBody().toString().replace("txt:", "").replaceAll("\"", "");
                        return message.getStringAttribute("nickName", "剪工用户") + ":" + s;
                    } else if (message.getType() == EMMessage.Type.VOICE) {
                        return message.getStringAttribute("nickName", "剪工用户") + ":[语音]";
                    } else if (message.getType() == EMMessage.Type.IMAGE) {
                        return message.getStringAttribute("nickName", "剪工用户") + ":[图片]";
                    }
                    return "您有新的聊天消息";
                }

                @Override
                public Intent getLaunchIntent(EMMessage message) {
                    //设置点击通知栏跳转事件
//                if (Utils.isForeground(appContext,"com.asktgapp.user.activity.MainActivity.class")){}
                    Intent intent = new Intent(appContext, MainActivity.class);
                    intent.putExtra("flag", 123);
                    //有电话时优先跳转到通话页面
//                if(isVideoCalling){
//                    intent = new Intent(appContext, VideoCallActivity.class);
//                }else if(isVoiceCalling){
//                    intent = new Intent(appContext, VoiceCallActivity.class);
//                }else{
//                    ChatType chatType = message.getChatType();
//                    if (chatType == ChatType.Chat) { // 单聊信息
//                        intent.putExtra("userId", message.getFrom());
//                        intent.putExtra("chatType", Constant.CHATTYPE_SINGLE);
//                    } else { // 群聊信息
//                        // message.getTo()为群聊id
//                        intent.putExtra("userId", message.getTo());
//                        if(chatType == ChatType.GroupChat){
//                            intent.putExtra("chatType", Constant.CHATTYPE_GROUP);
//                        }else{
//                            intent.putExtra("chatType", Constant.CHATTYPE_CHATROOM);
//                        }
//
//                    }
//                }
                    return intent;
                }
            });

    }

    protected void registerMessageListener() {
        if (easeUI != null)
            easeUI.setSettingsProvider(new EaseUI.EaseSettingsProvider() {

                @Override
                public boolean isSpeakerOpened() {
                    return true;
                }

                @Override
                public boolean isMsgVibrateAllowed(EMMessage message) {
                    return true;
                }

                @Override
                public boolean isMsgSoundAllowed(EMMessage message) {
                    return true;
                }

                @Override
                public boolean isMsgNotifyAllowed(EMMessage message) {
//                if(message == null){
//                    return demoModel.getSettingMsgNotification();
//                }
//                if(!demoModel.getSettingMsgNotification()){
//                    return false;
//                }else{
//                    String chatUsename = null;
//                    List<String> notNotifyIds = null;
//                    // get user or group id which was blocked to show message notifications
//                    if (message.getChatType() == EMMessage.ChatType.Chat) {
//                        chatUsename = message.getFrom();
//                        notNotifyIds = demoModel.getDisabledIds();
//                    } else {
//                        chatUsename = message.getTo();
//                        notNotifyIds = demoModel.getDisabledGroups();
//                    }
//
//                    if (notNotifyIds == null || !notNotifyIds.contains(chatUsename)) {
//                        return true;
//                    } else {
//                        return false;
//                    }
//                }
                    return true;
                }
            });
    }


    public static void reset() {

        if (!EMClient.getInstance().isLoggedInBefore()) {
            loginIn();
            return;
        }

        EMClient.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {
                LogUtil.LogI("Hxmsg", "logout onSuccess");
                loginIn();

            }

            @Override
            public void onError(int i, String s) {
                LogUtil.LogI("Hxmsg", "logout onError");
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }


    public static void loginIn() {
        if (EMClient.getInstance().isLoggedInBefore()) {
            Log.i("Hxmsg", "已经在线！");
            EMClient.getInstance().chatManager().loadAllConversations();
            return;
        }

        MyApplication application = MyApplication.getInstance();
        if (application == null)
            return;

        if (Util.isEmpty(PreferencesUtil.getString(application, PreferencesUtil.USER_ID))) {
            //APP未登录的情况下 不允许登录环信
            return;
        }
        String huanxin_id = PreferencesUtil.getString(application, PreferencesUtil.KEY_HX_ID);
        if (Util.isEmpty(huanxin_id)) {
            huanxin_id = PreferencesUtil.getString(application, PreferencesUtil.KEY_PHONE);
        }
        if (TextUtils.isEmpty(huanxin_id)) {
            Log.i("Hxmsg", "huanxin_id 为空！");
            return;
        }

        EMClient.getInstance().login(huanxin_id, "123456", new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().chatManager().loadAllConversations();
                Log.i("Hxmsg", "登录成功！");
            }

            @Override
            public void onError(int i, String s) {
                Log.i("Hxmsg", "登录失败！");
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    public static void login(String hxid) {
        if (EMClient.getInstance().isLoggedInBefore()) {
            Log.i("Hxmsg", "已经在线！");
            return;
        }
        EMClient.getInstance().login(hxid, "123456", new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.i("Hxmsg", "登录成功！");
            }

            @Override
            public void onError(int i, String s) {
                Log.i("Hxmsg", "登录失败！");
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    public static void loginOut() {
        if (!EMClient.getInstance().isLoggedInBefore())
            return;
        EMClient.getInstance().logout(true);
    }

    private EMOptions initChatOptions() {
        Log.d(TAG, "init HuanXin Options");

        EMOptions options = new EMOptions();
        options.setAutoLogin(false);
        // set if accept the invitation automatically
//        options.setAcceptInvitationAlways(false);
        // set if you need read ack
//        options.setRequireAck(true);
        // set if you need delivery ack
//        options.setRequireDeliveryAck(false);

//        options.setAppKey(BiuEaseConstant.APP_KEY);

        return options;
    }

    protected void setEaseUIProviders() {
        // set profile provider if you want easeUI to handle avatar and nickname
        easeUI.setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {

            @Override
            public EaseUser getUser(String username) {
                return getUserInfo(username);
            }
        });


    }

    /**
     * group change listener
     */
    private EaseUser getUserInfo(String username) {
        // To get instance of EaseUser, here we get it from the user list in memory
        // You'd better cache it if you get it from your server
        EaseUser user = null;
        user = contactList.get(username);
        // if user is not in your contacts, set inital letter for him/her
        if (user == null) {
            user = new EaseUser(username);
            EaseCommonUtils.setUserInitialLetter(user);
        }
        return user;
    }

    /**
     * 开始聊天
     *
     * @param context      easeInfo 环信额外信息
     * @param toUserIDName 环信id 电话号码
     * @param
     * @param toHeadImg
     */
    public void beginSingleCha(final Context context, final String easeInfo, final String toUserIDName, final String jg_username, final String toHeadImg, final String toUserId, final int type, final String cid, final int askType) {

//        String token = PreferencesUtil.getString(context, PreferencesUtil.KEY_TOKEN);
//        if (TextUtils.isEmpty(token) || TextUtils.isEmpty(toUserIDName)) {
//            return;
//        }
//        Apiservice apiservice = ApiUtil.getInstance().create();
//        HashMap params = new HashMap();
//        params.put("userid", PreferencesUtil.getString(context, PreferencesUtil.USER_ID));
//        Call<ApiResponseBody<UserInfoVO>> call = apiservice.getUserInfo(params);
//        call.enqueue(new Callback<ApiResponseBody<UserInfoVO>>() {
//            @Override
//            public void onResponse(Call<ApiResponseBody<UserInfoVO>> call, Response<ApiResponseBody<UserInfoVO>> response) {
//                if (response.isSuccessful()) {
//                    UserInfoVO mUserInfo = response.body().getResult();
//                    if (mUserInfo.getHasTixianPwd() == 0) {
//                        PreferencesUtil.putBoolean(context, PreferencesUtil.KEY_HAS_TX_PWD, false);
//                    } else {
//                        PreferencesUtil.putBoolean(context, PreferencesUtil.KEY_HAS_TX_PWD, true);
//                    }
//                    if (mUserInfo.getIsEngineer() == 1) {
//                        PreferencesUtil.putBoolean(context, PreferencesUtil.KEY_IS_ENGINEER, true);
//                    } else {
//                        PreferencesUtil.putBoolean(context, PreferencesUtil.KEY_IS_ENGINEER, false);
//                    }
//                    PreferencesUtil.putString(context, PreferencesUtil.KEY_PHONE, mUserInfo.getPhone());
//                    PreferencesUtil.putString(context, PreferencesUtil.HEAD_IMG, mUserInfo.getUserPic());
//                    if (mUserInfo.getIs_clear() == 1) {
//                        Toast.makeText(context, "自己或对方不在线,请去个人中心->加入剪工->联系邮箱联系客服", Toast.LENGTH_LONG).show();
//                        return;
//                    } else if (mUserInfo.getIsEngineer() == 1) {
//                        begin(context, easeInfo, toUserIDName, jg_username, toHeadImg, toUserId, 2, cid, askType);
//                    } else {
//                        begin(context, easeInfo, toUserIDName, jg_username, toHeadImg, toUserId, 0, cid, askType);
//                    }
//                } else {
//
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ApiResponseBody<UserInfoVO>> call, Throwable t) {
//                ApiException apiException = ExceptionHandle.handleException(t);
//                if (apiException.isTokenInvalid()) {
//                    Toast.makeText(context, apiException.getMessage(), Toast.LENGTH_SHORT).show();
//
//                }
//            }
//        });

//        if () {
//                        begin(context, easeInfo, toUserIDName, jg_username, toHeadImg, toUserId, 2, cid, askType);
//                    } else {
//                        begin(context, easeInfo, toUserIDName, jg_username, toHeadImg, toUserId, 0, cid, askType);
//                    }

    }

    public void beginSingleChat(Context context, String easeInfo, String toUserIDName, String jg_username, String toHeadImg, String toUserId, int type, String cid, int askType) {
        String curUserName = PreferencesUtil.getString(context, PreferencesUtil.KEY_PHONE);
        String curNickName = PreferencesUtil.getString(context, PreferencesUtil.KEY_NAME);
        String curImageHead = PreferencesUtil.getString(context, PreferencesUtil.HEAD_IMG);

        EaseUser curUser = new EaseUser(curUserName);
        curUser.setNickname(curNickName);
        curUser.setAvatar(curImageHead);
        contactList.put(curUserName, curUser);

        EaseUser toUser = new EaseUser(toUserIDName);
        toUser.setNickname(jg_username);
        toUser.setAvatar(toHeadImg);
        contactList.put(toUserIDName, toUser);

        Intent intent = new Intent(context, ChatActivity.class);
        // open calling activity if there is call
        intent.putExtra("easeInfo", easeInfo);
        intent.putExtra(EaseConstant.EXTRA_USER_ID, toUserIDName);
        intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
        intent.putExtra("toUserId", toUserId);
        intent.putExtra("jg_username", jg_username);
        intent.putExtra("type", type);
        intent.putExtra("cid", cid);
        intent.putExtra("headimg", toHeadImg);
        //0 立即咨询 1二手机代检 2故障代检
        intent.putExtra("askType", askType);
        context.startActivity(intent);
    }


    public void beginNewSingleCha(final Context context, final String easeInfo, final String toUserIDName, final String jg_username, final String toHeadImg, final String toUserId, final int type, final String cid, final int askType) {

//        String token = PreferencesUtil.getString(context, PreferencesUtil.KEY_TOKEN);
//        if (TextUtils.isEmpty(token) || TextUtils.isEmpty(toUserIDName)) {
//            return;
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(context, PreferencesUtil.USER_ID));
        Call<ApiResponseBody<UserInfoVO>> call = apiservice.getUserInfo(params);
        call.enqueue(new Callback<ApiResponseBody<UserInfoVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<UserInfoVO>> call, Response<ApiResponseBody<UserInfoVO>> response) {
                if (response.isSuccessful()) {
                    UserInfoVO mUserInfo = response.body().getResult();
                    if (mUserInfo.getHasTixianPwd() == 0) {
                        PreferencesUtil.putBoolean(context, PreferencesUtil.KEY_HAS_TX_PWD, false);
                    } else {
                        PreferencesUtil.putBoolean(context, PreferencesUtil.KEY_HAS_TX_PWD, true);
                    }
                    if (mUserInfo.getIsEngineer() == 1) {
                        PreferencesUtil.putBoolean(context, PreferencesUtil.KEY_IS_ENGINEER, true);
                    } else {
                        PreferencesUtil.putBoolean(context, PreferencesUtil.KEY_IS_ENGINEER, false);
                    }
                    PreferencesUtil.putString(context, PreferencesUtil.KEY_PHONE, mUserInfo.getPhone());
                    PreferencesUtil.putString(context, PreferencesUtil.HEAD_IMG, mUserInfo.getUserPic());
                    if (mUserInfo.getIs_clear() == 1) {
                        Toast.makeText(context, "自己或对方不在线,请去个人中心->加入剪工->联系邮箱联系客服", Toast.LENGTH_LONG).show();
                        return;
                    } else if (mUserInfo.getIsEngineer() == 1) {
//                        beginNew(context, easeInfo, toUserIDName, jg_username, toHeadImg, toUserId, 2, cid, askType);
//
//                    } else {
//                        beginNew(context, easeInfo, toUserIDName, jg_username, toHeadImg, toUserId, 0, cid, askType);

                    }
                } else {

                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<UserInfoVO>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    Toast.makeText(context, apiException.getMessage(), Toast.LENGTH_SHORT).show();

                }
            }
        });


//        }


    }

    public void beginNewSingleChat(final Context context, String easeInfo, String toUserIDName, String jg_username, String toHeadImg, String toUserId, int type, String cid, int askType) {
        String curUserName = PreferencesUtil.getString(context, PreferencesUtil.KEY_PHONE);
        String curNickName = PreferencesUtil.getString(context, PreferencesUtil.KEY_NAME);
        String curImageHead = PreferencesUtil.getString(context, PreferencesUtil.HEAD_IMG);

        EaseUser curUser = new EaseUser(curUserName);
        curUser.setNickname(curNickName);
        curUser.setAvatar(curImageHead);
        contactList.put(curUserName, curUser);

        EaseUser toUser = new EaseUser(curUserName);
        toUser.setNickname(jg_username);
        toUser.setAvatar(toHeadImg);
        contactList.put(toUserIDName, toUser);

        Intent intent = new Intent(context, ChatActivity.class);
        // open calling activity if there is call
        intent.putExtra("easeInfo", easeInfo);
        intent.putExtra(EaseConstant.EXTRA_USER_ID, toUserIDName);
        intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
        intent.putExtra("toUserId", toUserId);
        intent.putExtra("jg_username", jg_username);
        intent.putExtra("type", type);
        intent.putExtra("cid", cid);
        intent.putExtra("headimg", toHeadImg);
        //0 立即咨询 1二手机代检 2故障代检
        intent.putExtra("askType", askType);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    public void EngineerbeginChat(Context context, String easeInfo, String toUserIDName, String toUserName, String toHeadImg, String toUserId) {

        String curUserName = PreferencesUtil.getString(context, PreferencesUtil.KEY_PHONE);
        String curNickName = PreferencesUtil.getString(context, PreferencesUtil.KEY_NAME);
        String curImageHead = PreferencesUtil.getString(context, PreferencesUtil.HEAD_IMG);

        EaseUser curUser = new EaseUser(curUserName);
        curUser.setNickname(curNickName);
        curUser.setAvatar(curImageHead);
        contactList.put(curUserName, curUser);

        EaseUser toUser = new EaseUser(curUserName);
        toUser.setNickname(toUserName);
        toUser.setAvatar(toHeadImg);
        contactList.put(toUserIDName, toUser);

        Intent intent = new Intent(context, ChatActivity.class);
        // open calling activity if there is call
        intent.putExtra("easeInfo", easeInfo);
        intent.putExtra(EaseConstant.EXTRA_USER_ID, toUserIDName);
        intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
        intent.putExtra("toUserId", toUserId);
        intent.putExtra("jg_username", toUserName);
        intent.putExtra("headimg", toHeadImg);
        context.startActivity(intent);

    }

    /**
     * if ever logged in
     *
     * @return
     */
    public boolean isLoggedIn() {
        return EMClient.getInstance().isLoggedInBefore();
    }

    /**
     * logout
     *
     * @param unbindDeviceToken whether you need unbind your device token
     * @param callback          callback
     */
    public void logout(boolean unbindDeviceToken, final EMCallBack callback) {
        Log.d(TAG, "logout: " + unbindDeviceToken);
        EMClient.getInstance().logout(unbindDeviceToken, new EMCallBack() {

            @Override
            public void onSuccess() {
                Log.d(TAG, "logout: onSuccess");
                if (callback != null) {
                    callback.onSuccess();
                }

            }

            @Override
            public void onProgress(int progress, String status) {
                if (callback != null) {
                    callback.onProgress(progress, status);
                }
            }

            @Override
            public void onError(int code, String error) {
                Log.d(TAG, "logout: onSuccess");
                if (callback != null) {
                    callback.onError(code, error);
                }
            }
        });
    }

    /**
     * get instance of EaseNotifier
     *
     * @return
     */
    public EaseNotifier getNotifier() {
        return easeUI.getNotifier();
    }

    /**
     * save single contact
     */
    public void saveContact(EaseUser user) {
        contactList.put(user.getUsername(), user);
    }

    public void pushActivity(Activity activity) {
        easeUI.pushActivity(activity);
    }

    public void popActivity(Activity activity) {
        easeUI.popActivity(activity);
    }


}
